layui.use(['form','jquery', 'dtree', 'backend', 'eleTree'],function(){
    let form = layui.form;
    let $ = layui.jquery;
    let dtree = layui.dtree;
    let backend = layui.backend;
    let eleTree = layui.eleTree;

    let eleTreeObj = null;
    let dTreeSelectValue = $("#form-pid").data('value');

    let eleTreeConfig = {
        el: '#form-auth',
        url: '/admin/role/authselect',
        where : {
            pid : dTreeSelectValue,
            id : $("#form-auth").data('id')
        },
        showCheckbox: true,
        response: {   // 对于后台数据重新定义名字
            statusName: "code",
            statusCode: 1,
            dataName: "data"
        },
        isDefaultChangePstatus:true,
        checkOnClickNode: true,
        request: {     // 对后台返回的数据格式重新定义
            name: "title",
            key: "id",
            children: "childlist",
            checked: "checked",
            disabled: "disabled",
            isLeaf: "isLeaf"
        },
    };

    dtree.render({
        elem: "#form-pid",
        initLevel: "1",
        method: 'get',
        response: {
            statusName: "code",
            statusCode: "1",
            message:"msg",
            rootName:"data",
            treeId:"id",
            parentId:"pid",
            title:"nickname",
            basicData: "basicData",
            childName: "children"
        },
        url: "/admin/role/select",
        select: true,
        dataStyle:"layuiStyle",
        selectCardHeight: "150",
        selectInputName: {
            nodeId: "form[pid]",
            context: ""
        }
    });

    eleTreeObj = eleTree(eleTreeConfig);

    dtree.on("changeSelect('form-pid')" ,function(obj){
        if (obj.param['form[pid]'] != undefined && obj.param['form[pid]'] != dTreeSelectValue) {
            dTreeSelectValue = obj.param['form[pid]'];
            eleTreeConfig.where.pid = obj.param['form[pid]'];
            eleTreeObj.reload(eleTreeConfig);
        }
    });

    form.on('submit(save)', function(data){
        let eleTreeSelect = eleTreeObj.getChecked(false, true);
        let menuIds = [];
        layui.each(eleTreeSelect, function (k,v) {
            menuIds.push(v.id);
        })
        data.field['form[menusids]'] = menuIds;
        let loading = layer.load();
        $.ajax({
            url: data.form.action,
            data: data.field,
            type:'post',
            success:function(res){
                if(res.code == 1){
                    layer.msg(res.msg,{icon:1,time:1000},function(){
                        backend.api.close();
                    });
                }else{
                    layer.confirm(res.msg, {icon: 3, title:'警告'}, function(index){
                        layer.close(index);
                    });
                }
            },
            complete : function () {
                layer.close(loading);
            }
        });
        return false;
    });
});
